using Devil;
using UnityEditor;
using UnityEngine;

namespace GameToolkit.Editor
{
    public static class EditorMenu
    {
        public static System.Type GetScriptType(string file)
        {
            var importer = AssetImporter.GetAtPath(file) as MonoImporter;
            if (importer == null)
                return null;
            var script = importer.GetScript();
            if (script == null)
                return null;
            return script.GetClass();
        }
        
        [MenuItem("CONTEXT/MonoScript/Create ScritableObject", true)]
        static bool IsScriptableObject(MenuCommand cmd)
        {
            var path = AssetDatabase.GetAssetPath(cmd.context);
            if (string.IsNullOrEmpty(path))
                return false;
            var type = GetScriptType(path);
            if (type == null || !GlobalUtil.IsTypeInheritedFrom(type, typeof(ScriptableObject), false))
                return false;
            return true;
        }

        [MenuItem("CONTEXT/MonoScript/Create ScritableObject")]
        static void CreateScriptableObject(MenuCommand cmd)
        {
            var path = AssetDatabase.GetAssetPath(cmd.context);
            if (string.IsNullOrEmpty(path))
                return;
            var type = GetScriptType(path);
            if (type == null || !GlobalUtil.IsTypeInheritedFrom(type, typeof(ScriptableObject), false))
                return;
            var file = EditorUtility.SaveFilePanelInProject("Create " + type.Name, type.Name, "asset", "Create ScriptableObject");
            if (string.IsNullOrEmpty(file))
                return;
            var asset = ScriptableObject.CreateInstance(type);
            asset.name = NativeFileSystem.GetFileName(file, true);
            if (NativeFileSystem.HasFile(file))
            {
                AssetDatabase.AddObjectToAsset(asset, file);
            }
            else
            {
                AssetDatabase.CreateAsset(asset, file);
            }
            AssetDatabase.ImportAsset(file);
            Selection.activeObject = asset;
        }
    }
}
